package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    WareSkuDao wareSkuDao;
    @Autowired
    WareOrderTaskService wareOrderTaskService;
    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();

        /**
         *    wareId: 123,//仓库id
         *    skuId: 123//商品id
         */
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId) && !"0".equalsIgnoreCase(skuId)) {
            wrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId) && !"0".equalsIgnoreCase(wareId)) {
            wrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long wareId, Integer skuNum, Long skuId) {
        // 1、查询商品库存是否存在
        List<WareSkuEntity> wareSkuEntityList = this.list(new QueryWrapper<WareSkuEntity>()
                .eq("sku_id", skuId)
                .eq("ware_id", wareId));
        // 1.1 没有该商品
        if (wareSkuEntityList == null && wareSkuEntityList.size() < 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStockLocked(0);
            // 1.2 查询出SkuInfo对象
            R skuInfo = productFeignService.getSkuInfoBySkuId(skuId);
            // 1.3 拿到返回结果转换成Map
            Map<String, Object> map = (Map<String, Object>) skuInfo.get("skuInfo");
            // 1.4 状态码为0请求成功
            if (skuInfo.getCode() == 0) {
                // 1.5 设置skuName
                wareSkuEntity.setSkuName((String) map.get("skuName"));
            }
            // 1.6 保存库存信息
            this.save(wareSkuEntity);
        } else {
            //1.7 已有该对象，更新库存
            wareSkuDao.updateWare(wareId, skuId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> hasStock(List<Long> skuIds) {
        List<SkuHasStockVo> skuHasStockVoList = skuIds.stream().map(item -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            // 1.1、根据skuid查询库存数
            Long count = wareSkuDao.hashStock(item);
            skuHasStockVo.setSkuId(item);
            // 1.2、验证查询库存数是否为空
            skuHasStockVo.setHasStock(count == null ? false : count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return skuHasStockVoList;
    }

    /**
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        // 1、保存库存工作单
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);

        // 2、按照下单的收货地址找到最近的仓库进行发货
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> stocks = locks.stream().map(orderItemVo -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = orderItemVo.getSkuId();
            // 商品skuid
            stock.setSkuId(skuId);
            // 商品购买数量
            stock.setNum(orderItemVo.getCount());
            List<Long> wareIds = wareSkuDao.ListWareIdHasStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        for (SkuWareHasStock stock : stocks) {
            // 标识库存是否锁定成功
            Boolean skuStocked = false;
            // 商品skuid
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            // 库存为空抛出异常
            if (wareIds == null && wareIds.size() == 0) {
                // 抛出库存为空并带上skuid
                throw new NoStockException(skuId);
            }
            // 开始遍历库存id
            for (Long wareId : wareIds) {
                // 根据skuid还有wareid来进行锁定库存
                Long count = wareSkuDao.LockSkuStock(skuId, wareId, stock.getNum());
                if (count == 1) {
                    // 库存锁定成功
                    skuStocked = true;
                    // 创建库存工作单保存当前记录
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity(null,
                            stock.getSkuId(),
                            "",
                            stock.getNum(),
                            taskEntity.getId(),
                            wareId, 1L);
                    // 保存库存工作单
                    wareOrderTaskDetailService.save(detailEntity);
                    // 准备To用来发送到MQ中
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    // 库存工作单id
                    stockLockedTo.setId(detailEntity.getId());
                    // 库存工作单
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    // 将库存工作单属性拷贝到to中
                    BeanUtils.copyProperties(detailEntity, stockDetailTo);
                    stockLockedTo.setDetail(stockDetailTo);
                    // 给MQ发送消息，库存锁定成功
                    rabbitTemplate.convertAndSend("stock-event-exchange",
                            "stock.locked",
                            stockLockedTo);
                } else {
                    // 尝试锁定下一个仓库
                }
            }
            if (skuStocked == false) {
                // 仓库没锁住
                throw new NoStockException(skuId);
            }
        }
        // 库存锁定成功
        return true;
    }

    /**
     * 解锁库存
     * @param lockedTo
     */
    @Override
    public void unLockStock(StockLockedTo lockedTo) {
        // 工作单详情
        StockDetailTo detail = lockedTo.getDetail();
        // 工作单详情id
        Long detailId = detail.getId();
        // 查询到库存工作单详情
        WareOrderTaskDetailEntity taskDetailEntity = wareOrderTaskDetailService.getById(detailId);
        if (taskDetailEntity != null) {
            // 解锁库存
            // 库存工作单id
            Long id = lockedTo.getId();
            // 查询到库存工作单
            WareOrderTaskEntity TaskEntity = wareOrderTaskService.getById(id);
            // 拿到订单号
            String orderSn = TaskEntity.getOrderSn();
            // 根据订单号查询订单的状态
            R orderStatus = orderFeignService.getOrderStatus(orderSn);
            if (orderStatus.getCode() == 0) {
                OrderVo data = orderStatus.getData(new TypeReference<OrderVo>() {
                });
                // 订单状态为已关闭,那么就需要解锁库存
                if (data == null || data.getStatus() == 4) {
                    // 库存工作单锁定状态为锁定才进行解锁
                    if (taskDetailEntity.getLockStatus() == 1) {
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                // 消息被拒绝后重新放到队列里面，让别人继续消费解锁
                throw new RuntimeException("远程服务失败");
            }
        }
    }

    /**
     * 防止订单服务卡顿，导致订单服务消息一直改不了，库存消息优先到期，查订单状态新建状态，什么都不做了就走了
     * 导致卡顿的订单，永远不能解锁订单
     * @param orderTo 订单对象
     */
    @Override
    public void unLockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        // 查询最新库存工作单，并且查看库存工作单中的锁定状态，防止重复解锁库存
        WareOrderTaskEntity taskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long taskId = taskEntity.getId();
        // 根据工作单id，找到没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> detailEntities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", taskId)
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity detailEntity : detailEntities) {
            // 解锁库存
            this.unLockStock(detailEntity.getSkuId()
                    ,detailEntity.getWareId()
                    ,detailEntity.getSkuNum()
                    ,detailEntity.getId());
        }
    }

    /**
     * 解锁库存
     * @param skuId        商品skuid
     * @param wareId       库存id
     * @param num          数量
     * @param taskDetailId 订单详情id
     */
    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        // 库存解锁
        wareSkuDao.unLockStock(skuId, wareId, num);
        // 更新库存工作单的状态为已解锁
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(taskDetailId);
        // 更新库存状态为已解锁
        detailEntity.setLockStatus(2L);
        wareOrderTaskDetailService.updateById(detailEntity);
    }

    /**
     * 仓库是否有库存
     */
    @Data
    class SkuWareHasStock {
        /**
         * skuid
         */
        private Long skuId;
        /**
         * 数量
         */
        private Integer num;
        /**
         * 仓库id
         */
        private List<Long> wareId;
    }

}